#include <im_utilities.h>
#include <check.h>
#include <stdio.h>
#include <stdlib.h>

#define ARRAY_SIZE (1024 * 1024)


static int cmp_int_with_data(IMConstPointer a, IMConstPointer b, IMPointer data)
{
	if (data != NULL)
		return 0;	
	return *((int *)a) - *((int *)b);
}

START_TEST(utilities_test_qsort_with_data)
{
	int i = 0;
	int array[ARRAY_SIZE];
	/* Create a array */	
	for (i = 0; i < ARRAY_SIZE; i++) {
		array[i] = random();	
	}

	im_qsort_with_data ((IMConstPointer)array, ARRAY_SIZE, 
		sizeof(int),cmp_int_with_data, NULL);

	for (i = 0; i < ARRAY_SIZE - 1; i++) {
		fail_if (array[i] > array[i+1]);
	}
}
END_TEST

static int cmp_char (IMConstPointer a, IMConstPointer b)
{
	return *((char *)a) - *((char*)b);
}

START_TEST(utilities_test_lower_bound)
{
	char str[] = "123344556666789";

	char *p;

	p = im_lower_bound ((IMConstPointer)str, sizeof(str), 1, "4", cmp_char);
	fail_if ( (p - str) != 4);
	
}
END_TEST

START_TEST(utilities_test_upper_bound)
{
	char str[] = "123344556666789";

	char *p;

	p = im_upper_bound ((IMConstPointer)str, sizeof(str), 1, "4", cmp_char);
	fail_if ( (p - str) != 6);
	
}
END_TEST



Suite * utilities_suite (void)
{
	Suite *s;
	TCase *tc;
	
	s = suite_create ("utilities");
	
	tc = tcase_create ("qsort");
	suite_add_tcase (s, tc);
	tcase_add_test(tc, utilities_test_qsort_with_data);
	tcase_set_timeout (tc, 100);
	
	tc = tcase_create ("lower_bound");
	suite_add_tcase (s, tc);
	tcase_add_test(tc, utilities_test_lower_bound);
	tcase_set_timeout (tc, 100);
	
	tc = tcase_create ("upper_bound");
	suite_add_tcase (s, tc);
	tcase_add_test(tc, utilities_test_upper_bound);
	tcase_set_timeout (tc, 100);
	
	return s;
}



